<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button v-allow="'import'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="outLoad">excel导出</el-button>
          <el-button v-allow="'add'" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{prop:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <!-- 利用作用域插槽获取数据 -->
            <template #default="{row}">
              {{ formate(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column
            label="部门"
            prop="departmentName"
          />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <el-table-column label="账户状态" />
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="Assign(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="delEmp(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工的Dialog -->
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="hClose"
      >
        <EmpDialog ref="reForm" @success="hSuccess" @close="showDialog=false" />
      </el-dialog>
      <!-- 分配权限的Dialog -->
      <el-dialog title="分配权限" :visible.sync="showRoleDialog">
        <!-- 父传子 将id传递给子组件 -->
        <AssignRole v-if="showRoleDialog" :role-id="roleId" :list="list" @close="showRoleDialog=false" />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole.vue'
import EmpDialog from './empDialog.vue'
import PageTools from '@/components/PageTools'
import { getEmployees, delEmployees } from '@/api/employees'
import Employees from '@/constant/employees'
// 枚举
const hireType = Employees.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    PageTools,
    EmpDialog,
    AssignRole
  },
  data() {
    return {
      roleId: '',
      showRoleDialog: false,
      showDialog: false,
      list: [], // 存放获取的员工信息
      page: 1, // 页码值
      size: 2, // 每页的条数
      total: 0 // 获取的数据总数
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    Assign(id) {
      this.showRoleDialog = true
      this.roleId = id
    },
    // 格式化excel键名(英文-->中文)
    dataFormat(list) {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      let headers = []
      if (list[0]) {
        headers = Object.keys(list[0]).map(item => {
          return mapInfo[item]
        })
        // console.log(headers)
      }
      const data = list.map(item => {
        return Object.values(item)
      })
      return { headers, data }
    },
    async outLoad() {
      try {
        const res = await getEmployees(this.page, this.size)
        const { headers, data } = this.dataFormat(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
          console.log(excel)
          excel.export_json_to_excel({
            header: headers, // 表头 必填 ['姓名','年龄']
            data, // 具体数据 必填 [['张三',16],['李四',20]]
            filename: 'excel-list', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
          })
        })
      } catch (error) {
        console.log(error)
      }
    },
    // 删除员工
    delEmp(id) {
      this.$confirm('你确定要删除吗?').then(async() => {
        const res = await delEmployees(id)
        if (res.code !== 10000) return
        this.$message.success(res.message)
        this.loadEmployees()
      }).catch(error => console.log(error))
    },
    // 关闭弹层触发
    hClose() {
      this.$refs.reForm.resetForm()
    },
    // 添加角色
    hSuccess() {
      // 因为新添加的数据在服务器中还没获取 所以总数要加1
      this.total++
      // 获取最大的页码值
      const maxPage = Math.ceil(this.total / this.size)
      this.page = maxPage
      this.loadEmployees()
      this.showDialog = false
    },
    // 当前每页显示的数量
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployees()
    },
    // 当前页码值
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployees()
    },
    // 枚举格式化用户聘用信息
    formate(data) {
      return hireType[data] || '未知'
    },
    // 获取员工基本信息
    async loadEmployees() {
      const res = await getEmployees(this.page, this.size)
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    }
  }
}
</script>
